<?php

namespace app\ask\controller;

use think\Controller;

class Post extends Controller
{
    public function __construct()
    {
        parent::__construct();

        $this->BusinessModel = model('Business.Business');
        $this->PostModel = model('Post.Post');
        $this->CollectModel = model('Post.Collect');
        $this->CommentModel = model('Post.Comment');
    }

    // 首页获取帖子列表  我的提问帖子信息
    public function index()
    {
        if ($this->request->isPost()) {
            $page = $this->request->param('page', 1, 'trim');
            $cateid = $this->request->param('cateid', 0, 'trim');
            $keywords = $this->request->param('keywords', '', 'trim');
            $busid = $this->request->param('busid', 0, 'trim');

            $limit = 10;
            $offset = ($page - 1) * $limit;

            $where = [];

            if ($cateid) {
                $where['cateid'] = $cateid;
            }

            if (!empty($keywords)) {
                $where['title'] = ['like', "%$keywords%"];
            }
            if ($busid != 0) {
                $where['busid'] = $busid;
            }
            $list = $this->PostModel
                ->with(['cate', 'business'])
                ->where($where)
                ->order('createtime', 'desc')
                ->limit($offset, $limit)
                ->select();

            if ($list) {
                $this->success('返回帖子数据', null, $list);
                exit;
            } else {
                $this->error('暂无更多数据');
                exit;
            }
        }
    }

    // 发布帖子
    public function add()
    {
        if ($this->request->isPost()) {
            $title = $this->request->param('title', '', 'trim');
            $content = $this->request->param('content', '', 'trim');
            $point = $this->request->param('point', 0, 'trim');
            $cateid = $this->request->param('cateid', 0, 'trim');
            $busid = $this->request->param('busid', 0, 'trim');

            //确保用户是否存在
            $business = $this->BusinessModel->find($busid);

            if (!$business) {
                $this->error('用户不存在');
                exit;
            }

            //查看用户积分是否充足
            $UpdatePoint = bcsub($business['point'], $point);

            if ($UpdatePoint < 0) {
                $this->error('积分不足，请先充值');
                exit;
            }

            //帖子表、用户表、消费记录表
            $this->PostModel->startTrans();
            $this->BusinessModel->startTrans();

            //插入帖子
            $PostData = [
                'title' => $title,
                'content' => $content,
                'point' => $point,
                'busid' => $busid,
                'cateid' => $cateid,
                'status' => '0',
            ];

            $PostStatus = $this->PostModel->validate('common/Post/Post')->save($PostData);

            if ($PostStatus === FALSE) {
                $this->error($this->PostModel->getError());
                exit;
            }

            //更新用户积分
            $BusinessData = [
                'id' => $busid,
                'point' => $UpdatePoint
            ];

            $BusinessStatus = $this->BusinessModel->isUpdate(true)->save($BusinessData);

            if ($BusinessStatus === FALSE) {
                $this->PostModel->rollback();
                $this->error($this->BusinessModel->getError());
                exit;
            }

            if ($PostStatus === FALSE || $BusinessStatus === FALSE) {
                $this->BusinessModel->rollback();
                $this->PostModel->rollback();
                $this->error('发帖失败');
                exit;
            } else {
                $this->PostModel->commit();
                $this->BusinessModel->commit();
                $this->success('发帖成功', '/pages/post/info', ['postid' => $this->PostModel->id]);
                exit;
            }
        }
    }

    //查询帖子分类
    public function cate()
    {
        $list = model('Post.Cate')->order('weigh', 'asc')->select();

        if ($list) {
            $this->success('帖子分类', null, $list);
            exit;
        } else {
            $this->error('无帖子分类');
            exit;
        }
    }
    //编辑
    public function edit()
    {
        if ($this->request->isPost()) {
            $title = $this->request->param('title', '', 'trim');
            $content = $this->request->param('content', '', 'trim');
            $point = $this->request->param('point', 0, 'trim');
            $cateid = $this->request->param('cateid', 0, 'trim');
            $busid = $this->request->param('busid', 0, 'trim');
            $postid = $this->request->param('postid', 0, 'trim');


            //确保用户是否存在
            $business = $this->BusinessModel->find($busid);

            if (!$business) {
                $this->error('用户不存在');
                exit;
            }

            //确保帖子是存在
            $post = $this->PostModel->where(['id' => $postid, 'busid' => $busid])->find();

            if (!$post) {
                $this->error('帖子不存在');
                exit;
            }


            //查看用户积分是否充足
            $UpdatePoint = bcsub($business['point'], $point);

            if ($UpdatePoint < 0) {
                $this->error('积分不足，请先充值');
                exit;
            }

            //帖子表、用户表、消费记录表
            $this->PostModel->startTrans();
            $this->BusinessModel->startTrans();

            //编辑帖子
            $PostData = [
                'id' => $postid,
                'title' => $title,
                'content' => $content,
                'busid' => $busid,
                'cateid' => $cateid,
                'status' => '0',
            ];

            //积分
            if ($point > 0) {
                $PostData['point'] = bcadd($post['point'], $point);
            }


            $PostStatus = $this->PostModel->isUpdate(true)->save($PostData);

            if ($PostStatus === FALSE) {
                $this->error($this->PostModel->getError());
                exit;
            }

            //更新用户积分
            $BusinessData = [
                'id' => $busid,
                'point' => $UpdatePoint
            ];

            $BusinessStatus = $this->BusinessModel->isUpdate(true)->save($BusinessData);

            if ($BusinessStatus === FALSE) {
                $this->PostModel->rollback();
                $this->error($this->BusinessModel->getError());
                exit;
            }

            if ($PostStatus === FALSE || $BusinessStatus === FALSE) {
                $this->BusinessModel->rollback();
                $this->PostModel->rollback();
                $this->error('编辑帖子失败');
                exit;
            } else {
                $this->PostModel->commit();
                $this->BusinessModel->commit();
                $this->success('编辑帖子成功');
                exit;
            }
        }
    }

    public function info()
    {
        if ($this->request->isPost()) {
            $postid = $this->request->param('postid', 0, 'trim');
            $busid = $this->request->param('busid', 0, 'trim');

            $post = $this->PostModel->with(['business', 'cate'])->find($postid);

            if (!$post) {
                $this->error('暂无帖子信息');
                exit;
            }

            $business = $this->BusinessModel->find($busid);

            //如果有找到用户信息
            if ($business) {
                //查询收藏的状态
                $collect = model('Post.Collect')->where(['postid' => $postid, 'busid' => $busid])->find();

                if ($collect) {
                    //追加自定义数组元素
                    $post['collect'] = true;
                }
            }

            $this->success('返回帖子信息', null, $post);
            exit;
        }
    }

    //收藏
    public function collect()
    {
        if ($this->request->isPost()) {
            $postid = $this->request->param('postid', 0, 'trim');
            $busid = $this->request->param('busid', 0, 'trim');

            $business = $this->BusinessModel->find($busid);

            if (!$business) {
                $this->error('用户不存在');
                exit;
            }

            //查询这个是否有收藏过
            $where = ['busid' => $busid, 'postid' => $postid];

            $collect = $this->CollectModel->where($where)->find();

            if ($collect) {
                //有收藏过 要取消收藏 删除记录
                $result = $this->CollectModel->where(['id' => $collect['id']])->delete();

                if ($result === FALSE) {
                    $this->error('取消收藏失败');
                    exit;
                } else {
                    $this->success('取消收藏成功');
                    exit;
                }
            } else {
                //没收藏过  要新增插入
                $result = $this->CollectModel->save(['busid' => $busid, 'postid' => $postid]);

                if ($result === FALSE) {
                    $this->error('收藏失败');
                    exit;
                } else {
                    $this->success('收藏成功');
                    exit;
                }
            }
        }
    }

    // 点赞
    public function like()
    {
        if ($this->request->isPost()) {
            $postid = $this->request->param('postid', 0, 'trim');
            $busid = $this->request->param('busid', 0, 'trim');
            $comid = $this->request->param('comid', 0, 'trim');

            $business = $this->BusinessModel->find($busid);

            if (!$business) {
                $this->error('用户不存在');
                exit;
            }

            $comment = $this->CommentModel->find($comid);

            if (!$comment) {
                $this->error('评论不存在');
                exit;
            }

            $data = [
                'id' => $comid,
            ];

            //判断点过赞还是没点过赞
            $like_list = $comment['like_list'];

            //判断元素是否在数组内
            if (in_array($busid, $like_list)) {
                //如果有找到就说明点个赞，就是要取消点赞
                $index = array_search($busid, $like_list);
                unset($like_list[$index]);
            } else {
                $like_list[] = $busid;
            }

            if (empty($like_list)) {
                $data['like'] = NULL;
            } else {
                $data['like'] = implode(',', $like_list);
            }

            //更新
            $result = $this->CommentModel->isUpdate(true)->save($data);

            if ($result === FALSE) {
                $this->error('点赞失败');
                exit;
            } else {
                $this->success('点赞成功');
                exit;
            }
        }
    }

     //采纳
     public function accept()
     {
         if($this->request->isPost())
         {
             $comid = $this->request->param('comid', 0, 'trim');
             $postid = $this->request->param('postid', 0, 'trim');
             $busid = $this->request->param('busid', 0, 'trim');
 
             $business = $this->BusinessModel->find($busid);
 
             if(!$business)
             {
                 $this->error('用户不存在');
                 exit;
             }
 
             $comment = $this->CommentModel->find($comid);
 
             if(!$comment)
             {
                 $this->error('评论不存在');
                 exit;
             }
 
             //采纳人的信息
             $acceptid = isset($comment['busid']) ? $comment['busid'] : 0;
             $accept = $this->BusinessModel->find($acceptid);
 
             if(!$accept)
             {
                 $this->error('采纳人信息未知');
                 exit;
             }
 
             $where = ['id'=>$postid, 'busid'=>$busid];
             $post = $this->PostModel->where($where)->find();
 
             if(!$post)
             {
                 $this->error('帖子不存在');
                 exit;
             }
 
             //采纳不能采纳自己
             if($acceptid == $busid)
             {
                 $this->error('帖子不能采纳自己');
                 exit;
             }
 
             //帖子表(更新采纳人和状态)
             // 评论表改状态
             // 更改用户表
 
             $this->PostModel->startTrans();
             $this->CommentModel->startTrans();
             $this->BusinessModel->startTrans();
 
             //更新帖子表
             $PostData = [
                 'id' => $post['id'],
                 'status' => '1',
                 'accept' => $acceptid,
             ];
 
             $PostStatus = $this->PostModel->isUpdate(true)->save($PostData);
             
             if($PostStatus === FALSE)
             {
                 $this->error($this->PostModel->getError());
                 exit;
             }
 
             //评论表
             $CommentData = [
                 'id' => $comid,
                 'status' => '1',
             ];
 
             $CommentStatus = $this->CommentModel->isUpdate(true)->save($CommentData);
             
             if($CommentStatus === FALSE)
             {
                 $this->PostModel->rollback();
                 $this->error($this->CommentModel->getError());
                 exit;
             }
 
             //更新用户表
             $PostPoint = $post['point'];
             $BusPoint = $accept['point'];
 
             $UpdatePoint = bcadd($PostPoint, $BusPoint);
 
             $BusData = [
                 'id' => $accept['id'],
                 'point' => $UpdatePoint
             ];
 
             //更新用户积分
             $BusStatus = $this->BusinessModel->isUpdate(true)->save($BusData);
 
             if($BusStatus === FALSE)
             {
                 $this->CommentModel->rollback();
                 $this->PostModel->rollback();
                 $this->error($this->BusinessModel->getError());
                 exit;
             }
 
             if($PostStatus === FALSE || $CommentStatus === FALSE || $BusStatus === FALSE)
             {
                 $this->BusinessModel->rollback();
                 $this->CommentModel->rollback();
                 $this->PostModel->rollback();
                 $this->error('采纳失败');
                 exit;
             }else
             {
                 $this->PostModel->commit();
                 $this->CommentModel->commit();
                 $this->BusinessModel->commit();
                 $this->success('采纳成功');
                 exit;
             }
         }
     }
}
